package com.witmore.neutron.ai.web.service.impl;

import com.witmore.neutron.ai.db.entity.CooperationInquiryDO;
import com.witmore.neutron.ai.web.service.WechatWorkNotifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 企业微信通知服务实现类（空实现）
 *
 * @author 豆子高
 * @since 2025-09-17
 */
@Slf4j
@Service
public class WechatWorkNotifyServiceImpl implements WechatWorkNotifyService {

    public static final String WECHAT_WEBHOOK_END_POINT = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s";

    public static final String WECHAT_WEBHOOK_AI_KEY = "e620929d-efbb-437e-a286-3c3449dccac4";


    @Autowired
    private Environment environment;

    private String getEnvironmentProperty() {
        boolean prod = Arrays.asList(environment.getActiveProfiles()).contains("prod");
        if (prod) {
            return "【生产环境】\n";
        }
        boolean dev = Arrays.asList(environment.getActiveProfiles()).contains("dev");
        if (dev) {
            return "【开发环境】\n";
        }
        return "【异常环境】\n";
    }


    @Override
    public void sendCooperationInquiryNotify(CooperationInquiryDO inquiry) {
        // TODO: 实现企业微信通知发送逻辑
        log.info("【企业微信通知】收到合作咨询 - 公司：{}，联系人：{}，手机：{}，邮箱：{}，描述：{}",
                inquiry.getCompanyName(),
                inquiry.getContactName(),
                inquiry.getPhone(),
                inquiry.getEmail(),
                inquiry.getBusinessDesc());

        // 这里可以调用企业微信API发送消息
        // 1. 构建消息内容
        // 2. 调用企业微信webhook或API
        // 3. 处理发送结果
        String hookUrl = String.format(WECHAT_WEBHOOK_END_POINT, WECHAT_WEBHOOK_AI_KEY);
        String message = "【合作咨询】\n" +
                "公司：" + inquiry.getCompanyName() + "\n" +
                "联系人：" + inquiry.getContactName() + "\n" +
                "手机：" + inquiry.getPhone() + "\n" +
                "邮箱：" + inquiry.getEmail() + "\n" +
                "描述：" + inquiry.getBusinessDesc();
        this.sendTextToWeChatAsync(message, hookUrl);
        log.info("【企业微信通知】发送完成");
    }

    private void sendTextToWeChatAsync(String message, String hookUrl) {
        message = getEnvironmentProperty() + message;
        RestTemplate restTemplate = new RestTemplate();

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("msgtype", "text");
        Map<String, String> textContent = new HashMap<>();
        textContent.put("content", message);
        requestBody.put("text", textContent);
        restTemplate.postForObject(hookUrl, requestBody, String.class);
    }


}
